import React, {Component} from 'react';
import {View, Text, FlatList} from 'react-native';
import {List, Divider} from 'react-native-paper';
import request from '../../utils/request';
import AsyncStorage from '@react-native-community/async-storage';
export default class songItem extends Component {
  constructor(props) {
    super(props);
    this._handleFetchData();
    this.__handleGetUserId();
    this.state = {
      refreshing: false,
      song: {
        songId: '',
        songName: '',
        songSinger: '',
        songAlbum: '',
        songPhoto: '',
        songUrl: '',
        songIsVip: '',
        songStatus: '',
        songDesc: '',
      },
      songList: [],
    };
  }

  _handleFetchData() {
    request({
      url: '/song/all/',
      method: 'get',
    }).then(resp => {
      console.log(resp.obj);
      this.setState({refreshing: false});
      this.setState({
        songList: resp.obj,
      });
    });
  }

  __handleGetUserId() {
    const userId = '';
    AsyncStorage.getItem('userId').then(value => {
      this.setState({
        userId: value,
      });
    });
    console.log('getItem', userId);
    this.setState({
      userId: userId,
    });
  }

  _handleGetSongById(id) {
    console.log('songId', id);
    console.log('userId', this.state.userId);
    request({
      url: '/song/client/id',
      method: 'get',
      params: {
        songId: id,
        userId: this.state.userId,
      },
    }).then(resp => {
      console.log('get song:', resp.obj);
      this.setState({chooseSong: resp.obj});
      this.props.navigation.navigate('音乐播放', {
        song: resp.obj,
      });
    });
  }

  //列表项渲染
  __itemRender = (item, index, separators) => {
    const i = item.item;
    return (
      <List.Item
        title={i.songName}
        description={'歌手：' + i.songSinger + '  专辑：' + i.songAlbum}
        left={() => <List.Icon color="purple" icon="music" />}
        right={() => (
          <List.Icon color="purple" icon="arrow-right-drop-circle" />
        )}
        onPress={() => {
          this._handleGetSongById(i.songId);
        }}
      />
    );
  };

  //Key生成
  __keyExtractor = (item, index) => {
    return item.songId;
  };

  //行与行之间的分隔线组件
  __itemSeparatorComponent = () => {
    return <Divider />;
  };

  render() {
    return (
      <FlatList
        data={this.state.songList}
        ListEmptyComponent={() => {
          return <Text>没有数据</Text>;
        }}
        renderItem={this.__itemRender}
        keyExtractor={this.__keyExtractor}
        ItemSeparatorComponent={this.__itemSeparatorComponent}
        refreshing={this.state.refreshing}
        onRefresh={() => {
          this.setState({refreshing: true});
          this._handleFetchData();
        }}
      />
    );
  }
}
